package Java2Test.mythread.threadtest4;

import java.util.Random;

public class MyRunnable implements Runnable {
    static double redPackets = 100.0; // 总金额
    static int count = 3;             // 红包数量
    static final double MIN = 0.01;   // 单个红包最小金额

    /**
     * 需要用BigDecimal来完成
     */
    @Override
    public void run() {
        synchronized (MyRunnable.class) {
            // 1. 检查是否还有剩余红包
            if (count == 0) {
                System.out.println(Thread.currentThread().getName() + "没抢到");
                return;
            }

            double prize;
            // 2. 处理最后一个红包：直接拿走剩余金额
            if (count == 1) {
                prize = redPackets;
            } else {
                // 3. 计算当前红包最大可能金额
                //    确保剩余金额足够分配给后续红包（至少每个红包MIN元）
                double bounds = redPackets - (count - 1) * MIN;
                // 4. 生成随机金额 [0, bounds)
                prize = new Random().nextDouble() * bounds;
            }

            // 5. 确保单个红包金额不低于最小值
            if (prize < MIN) {
                prize = MIN;
            }

            // 6. 更新剩余金额和红包数量
            redPackets -= prize;
            count--;
            System.out.println(Thread.currentThread().getName() + "抢到了" + prize + "元");
        }
    }
}